<template>
  <div>
    <div v-if="row.actions.length > 2">
      <a
        @click="handleClickMore(row.actions[0].name, row)"
        v-if="showBtn(row.actions[0].label)"
        >{{ row.actions ? row.actions[0].label : "" }}</a
      >
      <Divider type="vertical" />
      <Dropdown @on-click="(name) => handleClickMore(name, row)" transfer>
        <a
          >更多
          <Icon type="ios-arrow-down" />
        </a>
        <DropdownMenu slot="list">
          <template v-for="(item, i) in row.actions.slice(1)">
            <DropdownItem v-if="showBtn(item.label)" :key="i" :name="item.name"
              >{{ item.label }}
            </DropdownItem>
          </template>
        </DropdownMenu>
      </Dropdown>
    </div>
    <div v-else>
      <a
        v-if="row.actions && showBtn(row.actions[0].label)"
        @click="handleClickMore(row.actions[0].name, row)"
        >{{ row.actions[0].label }}</a
      >
      <Divider v-if="row.actions && row.actions.length > 1" type="vertical" />
      <a
        v-if="
          row.actions && row.actions.length > 1 && showBtn(row.actions[1].label)
        "
        @click="handleClickMore(row.actions[1].name, row)"
        >{{ row.actions[1].label }}</a
      >
    </div>
    <Modal
      v-model="fenlei"
      title="关联分类"
      width="800"
      :fullscreen="true"
      @on-visible-change="visibleChange"
    >
      <Card title="已关联分类">
        <Row
          type="flex"
          class="height30"
          v-for="(item, index) in seletDataList"
          :key="index"
        >
          <Col>{{ item.fullNames }}</Col>
          <div @click="clickDel(item.uuid)">
            <Col>
              <Icon color="red" type="md-close" />
            </Col>
          </div>
        </Row>
      </Card>
      <Card title="关联分类">
        <div>
          <Row type="flex" style="width: 400px">
            <Input
              style="width: 250px"
              search
              enter-button
              placeholder=""
              v-model="searchKey"
              @on-search="inputSub"
            />
            <Button style="margin-left: 8px" @click="reSetSelect">重置</Button>
          </Row>
          <div>
            <Row style="margin-top: 20px" v-if="isSearch">搜索结果：</Row>
            <div v-if="isSearch && inputValue && inputValue.length > 0">
              <Row
                v-for="(item, index) in inputValue"
                :key="index"
                type="flex"
                class="height30"
              >
                <Col>{{ item.fullNames }}</Col>
                <Col style="margin-left: 10px"
                  ><Button type="primary" @click="searchRelation(item)"
                    >关联</Button
                  ></Col
                >
              </Row>
            </div>
            <Row v-if="isSearch && inputValue.length == 0">暂无搜索结果</Row>
            <Spin size="large" fix v-if="spinShow"></Spin>
          </div>
        </div>
        <Tree
          ref="tree"
          :data="rootDate"
          :load-data="loadData"
          @on-check-change="treeCheckChange"
          check-strictly
          show-checkbox
        />
      </Card>
      <div slot="footer">
        <Button @click="createRelate('2')">取消</Button>
        <Button type="primary" @click="createRelate('1')">确定</Button>
      </div>
    </Modal>
    <Modal
      v-model="showProp1"
      title="关联商品"
      width="800"
      :fullscreen="true"
      @on-ok="closeModal()"
      @on-cancel="closeModal()"
      :closable="false"
    >
      <Row type="flex">
        <Col span="8"
          >SPU编码：<Input
            v-model="spuNo"
            placeholder="请输入内容"
            style="width: 200px"
        /></Col>
        <Col span="8"
          >商品名称：<Input
            v-model="productName"
            placeholder="请输入内容"
            style="width: 200px"
        /></Col>
        <Col span="8">
          <Button type="primary" @click="linkAttributeBt('1')">查询</Button>
          <Button style="margin-left: 8px" @click="linkAttributeBt('0')"
            >清空</Button
          >
        </Col>
      </Row>
      <Row>
        <Tabs @on-click="tabsChang" style="margin: 10px">
          <TabPane label="未关联" name="Name12">
            <Button
              type="success"
              size="small"
              style="margin: 3px 0"
              @click="bathCreateFun"
              >批量关联</Button
            >
            <Table
              :columns="linkAttributeDataCol"
              :data="linkAttributeData"
              @on-select="handleBaseTablaeSelect($event, '1')"
              @on-select-all="handleSelectAll($event, '1')"
              @on-select-all-cancel="handleSelectAllCancel($event, '1')"
            >
              <template slot-scope="{ row, index }" slot="action">
                <Button
                  type="success"
                  size="small"
                  style="margin: 3px 0"
                  @click="linkAttributeSupply(row.uuid, '1')"
                  >关联</Button
                >
              </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
              <Page
                :total="totalNum"
                show-total
                show-sizer
                :current.sync="nowPage"
                @on-change="linkAttributeChang()"
                @on-page-size-change="handleChangePage"
              />
            </div>
          </TabPane>
          <TabPane label="已关联" name="Name11">
            <Button
              type="success"
              size="small"
              style="margin: 3px 0"
              @click="bathDelFun()"
              >批量取消关联</Button
            >
            <Table
              :columns="linkAttributeDataCol"
              :data="linkAttributeData"
              @on-select="handleBaseTablaeSelect($event, '2')"
              @on-select-all="handleSelectAll($event, '2')"
              @on-select-all-cancel="handleSelectAllCancel($event, '2')"
            >
              <template slot-scope="{ row, index }" slot="action">
                <Button
                  type="success"
                  size="small"
                  style="margin: 3px 0"
                  @click="linkAttributeSupply(row.productUuid, '0')"
                  >取消</Button
                >
              </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
              <Page
                :total="totalNum"
                show-total
                show-sizer
                :current.sync="nowPage"
                @on-change="linkAttributeChang()"
                @on-page-size-change="handleChangePage"
              />
            </div>
          </TabPane>
        </Tabs>
      </Row>
    </Modal>
  </div>
</template>
<script>
import dynamictableactions from '@/mixins/dynamictableactions'; // 混入通用代码
import { ApiRequest } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
export default {
  mixins: [dynamictableactions],
  data () {
    return {
      linkAttributeValue: 'Name12',
      spuNo: '',
      productName: '',
      linkAttributeDataCol: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '商品名称',
          key: 'productName',
          minWidth: 150
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          minWidth: 150
        },
        {
          title: '商品分类',
          key: 'categoryPath',
          minWidth: 150
        },
        {
          title: '管理区域',
          key: 'manageArea',
          minWidth: 150
        },
        {
          title: '规格参数',
          key: 'saleAttrInfo',
          minWidth: 150
        },
        {
          title: '品牌',
          key: 'brandName',
          minWidth: 150
        },
        {
          title: '操作',
          slot: 'action',
          width: 150,
          align: 'center'
        }
      ],
      data6: [
        {
          address: '传递到'
        }
      ],
      value: '',
      actions: [],
      fenlei: false,
      showProp1: false,
      rootDate: [],
      uuid: '', // 当前选中的uuid
      checkData: [],
      seletDataList: [],
      linkAttributeData: [],
      inputValue: [],
      isSearch: false,
      spinShow: false,
      searchKey: '',
      totalNum: 0,
      nowPage: 1,
      pageShow: 10, // 每页展示条数
      productUuidList: []
    };
  },
  created () {},
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  methods: {
    initData () {
      let data = {
        parentUuid: 'systemUuid'
      };
      ApiRequest(
        this.requestApi.getPlatCategorySubByParentUuid.url,
        this.requestApi.getPlatCategorySubByParentUuid.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          let myNewData = [];

          res.retData.forEach(item => {
            myNewData.push({
              title: item.categoryName,
              uuid: item.uuid,
              levelNum: item.levelNum,
              loading: false,
              disableCheckbox: true,
              disabled: true,
              children: []
            });
          });
          this.rootDate = myNewData;
        }
      });
    },
    initTopData () {
      let data = {
        scenceUuid: this.uuid
      };
      // 创建分类
      ApiRequest(
        this.requestApi.getRelateByScenceUuid.url,
        this.requestApi.getRelateByScenceUuid.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1' && res.retData !== null) {
          this.seletDataList = [];
          res.retData.forEach(element => {
            if (element.levelNum === '4') {
              this.seletDataList.push(element);
            }
          });
        } else {
          this.seletDataList = [];
        }
      });
    },
    // 重置,取消选中
    reSetSelect () {
      this.searchKey = '';
      this.initData();
      this.inputValue = [];
    },
    inputSub (value) {
      if (value) {
        this.spinShow = true;
        this.isSearch = true;
        let data = {
          categoryName: value
        };
        ApiRequest(
          this.requestApi.getByCategoryName.url,
          this.requestApi.getByCategoryName.type,
          data,
          true
        ).then(res => {
          this.spinShow = false;
          if (res.retStatus == '1') {
            if (res.retData.length > 0) {
              this.inputValue = res.retData;
            } else {
              this.inputValue = [];
            }
          }
        });
      } else {
        this.$Message.error('请输入搜索内容');
      }
    },
    // 模态框显示状态改变时触发
    visibleChange (type) {
      this.inputValue = [];
      this.isSearch = false;
      this.spinShow = false;
      this.searchKey = '';
    },
    // 单个搜索关联分类
    searchRelation (item) {
      this.spinShow = true;
      if (this.uuid && item.categoryUuids[item.categoryUuids.length - 1]) {
        let data = {
          categoryUuid: item.categoryUuids[item.categoryUuids.length - 1],
          scenceUuid: this.uuid
        };
        ApiRequest(
          this.requestApi.createSingleRelateScence.url,
          this.requestApi.createSingleRelateScence.type,
          data,
          true
        ).then(res => {
          if (res.retStatus === '1') {
            this.$Message.success('关联成功');
            this.spinShow = false;
            this.initTopData();
          }
        });
      }
    },
    tabsChang (name) {
      this.linkAttributeValue = name;
      this.linkAttributeChang(this.linkAttributeValue);
    },
    linkAttributeChang () {
      let searchParam = [];
      if (this.spuNo !== '') {
        this.spuNo = this.spuNo.replace(/ /g, ''); // 过滤掉空格
      }
      if (this.productName !== '') {
        this.productName = this.productName.replace(/ /g, '');
      }
      searchParam.push({ name: 'productName', value: this.productName });
      searchParam.push({ name: 'productName_q', value: 'Like' });
      searchParam.push({ name: 'spuNo', value: this.spuNo });
      searchParam.push({ name: 'spuNo_q', value: 'Like' });
      let data = {
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        searchParam: JSON.stringify(searchParam),
        sortName: '',
        sortType: ''
      };
      if (this.linkAttributeValue === 'Name11') {
        ApiRequest(
          '/sysback/category/scenecategoryspu/getRelByCondition?sceneCategoryUuid=' +
            this.uuid,
          'post',
          data,
          false
        ).then(res => {
          if (res.retStatus === '1') {
            this.linkAttributeData = res.retData.results;
            this.totalNum = res.retData.totalNum;
          }
        });
      } else {
        ApiRequest(
          '/sysback/category/scenecategoryspu/getNotRelByCondition?sceneCategoryUuid=' +
            '' +
            this.uuid,
          'post',
          data,
          false
        ).then(res => {
          if (res.retStatus === '1') {
            this.linkAttributeData = res.retData.results;
            this.totalNum = res.retData.totalNum;
          }
        });
      }
    },
    linkAttributeSupply (uuid, type) {
      if (type === '0') {
        // 取消关联
        let data = {
          sceneCategoryUuid: this.uuid,
          productUuidList: uuid
        };
        // 创建分类
        ApiRequest(
          '/sysback/category/scenecategoryspu/deleteRelate',
          'post',
          data,
          true
        ).then(res => {
          if (res.retStatus === '1') {
            this.linkAttributeChang(this.linkAttributeValue);
          }
        });
      } else {
        let data = {
          sceneCategoryUuid: this.uuid,
          productUuidList: uuid
        };
        //  关联
        ApiRequest(
          '/sysback/category/scenecategoryspu/createRelate',
          'post',
          data,
          true
        ).then(res => {
          if (res.retStatus === '1') {
            this.linkAttributeChang(this.linkAttributeValue);
          }
        });
      }
    },
    linkAttributeBt (type) {
      if (type === '0') {
        this.spuNo = '';
        this.productName = '';
      }
      this.linkAttributeChang();
    },
    closeModal () {},
    handleChangePage (val) {
      this.pageShow = val;
      this.$nextTick(() => {
        this.linkAttributeChang(this.linkAttributeValue);
      });
    },
    createRelate (type) {
      if (type === '1') {
        if (this.checkData === null) {
          this.$Message.error('尚未勾选分类!');
          return false;
        }
        let data = {
          categoryUuids: this.checkData.join(','),
          scenceUuid: this.uuid
        };
        // 创建分类
        ApiRequest(
          this.requestApi.createRelate.url,
          this.requestApi.createRelate.type,
          data,
          true
        ).then(res => {
          if (res.retStatus === '1') {
            this.$Message.success('提交成功');
            this.initData();
            this.initTopData();
            this.fenlei = false;
          }
        });
      } else {
        this.fenlei = false;
      }
    },
    clickDel (uuid) {
      let data = {
        categoryUuid: uuid,
        relUuids: this.uuid
      };
      // 删除已关联分类
      ApiRequest(
        this.requestApi.baseDelete.url,
        this.requestApi.baseDelete.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          this.$Message.success('删除成功');
          this.initTopData();
        }
      });
    },
    treeCheckChange () {
      let sdata = this.$refs.tree.getCheckedNodes();
      let data = [];
      sdata.forEach(item => {
        data.push(item.uuid);
        this._loadData(item.uuid, res => {});
      });
      this.checkData = data;
    },
    loadData (item, callback) {
      this._loadData(item.uuid, callback);
    },
    _loadData (code, callback) {
      let data = {
        parentUuid: code
      };
      // 创建分类
      ApiRequest(
        this.requestApi.getPlatCategorySubByParentUuid.url,
        this.requestApi.getPlatCategorySubByParentUuid.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          let myNewData = [];
          let isCheck = false;
          if (res.retData !== null) {
            this.seletDataList.forEach(item => {
              res.retData.forEach(item2 => {
                if (item.uuid === item2.uuid) {
                  isCheck = true;
                } else {
                  isCheck = false;
                }
              });
            });

            res.retData.forEach(item => {
              myNewData.push({
                title: item.categoryName,
                uuid: item.uuid,
                levelNum: item.levelNum,
                disableCheckbox: item.levelNum !== '4',
                disabled: item.levelNum !== '4',
                loading: false,
                checked: isCheck,
                children: []
              });
            });
            callback(myNewData);
          } else {
            callback(myNewData);
            this.$Message.info('该分类下没有子分类');
          }
        }
      });
    },
    handleClickMore (name, row) {
      const that = this;
      if (name === 'Delete') {
        this.$Modal.confirm({
          title: '删除操作',
          content: '确定删除此数据吗？',
          onOk: () => {
            let curBtnId = getBtnsId('删除');
            sessionStorage.setItem('buttonId', curBtnId);
            let data = {
              uuid: row.uuid
            };
            // 开始请求商品列表
            ApiRequest(
              this.requestApi.delTableList.url,
              this.requestApi.delTableList.type,
              data,
              true
            ).then(res => {
              if (res.retStatus === '1') {
                that.$Message.success('删除成功');
                that.actionsChange();
              }
            });
          }
        });
      } else if (name === 'Fenlei') {
        let curBtnId = getBtnsId('关联分类');
        sessionStorage.setItem('buttonId', curBtnId);
        this.fenlei = true;
        this.uuid = row.uuid;
        this.initData();
        this.initTopData();
      } else {
        let obj = {}; // 动作的对象信息
        row.actions.forEach(item => {
          if (name === item.name) {
            obj = item;
            return false;
          }
        });
        this.setTableRowData(row);
        if (obj.handleType === 'link') {
          let curBtnId = getBtnsId('编辑');
          sessionStorage.setItem('buttonId', curBtnId);
          // 操作类型为链接时，拼接参数跳转
          let jumpPath = this.jumpPath + obj.name;
          this.$router.push({ path: jumpPath, query: { uuid: row.uuid } });
        } else if (obj.handleType === 'fenlei') {
          // 操作类型为弹窗时 打开弹窗
        } else if (obj.handleType === 'prop1') {
          let curBtnId = getBtnsId('关联商品');
          sessionStorage.setItem('buttonId', curBtnId);
          // 操作类型为弹窗时 打开弹窗
          this.showProp1 = true;
          this.uuid = row.uuid;
          this.linkAttributeChang(this.linkAttributeValue);
          // this.initData();
          // this.initTopData();
        } else if (obj.handleType === 'audit') {
        }
      }
    },
    // 全选
    handleSelectAll (row, type) {
      this.productUuidList = [];
      if (type === '1') {
        row.forEach(element => {
          this.productUuidList.push(element.uuid);
        });
      } else {
        row.forEach(element => {
          this.productUuidList.push(element.productUuid);
        });
      }
    },
    // 取消全选
    handleSelectAllCancel () {
      this.productUuidList = [];
    },
    // 单独选择操作
    handleBaseTablaeSelect (row, type) {
      this.productUuidList = [];
      if (type === '1') {
        row.forEach(element => {
          this.productUuidList.push(element.uuid);
        });
      } else {
        row.forEach(element => {
          this.productUuidList.push(element.productUuid);
        });
      }
    },
    // 批量关联
    bathCreateFun () {
      let data = {
        sceneCategoryUuid: this.uuid,
        productUuidList: this.productUuidList.join(',')
      };
      // 创建分类
      ApiRequest(
        '/sysback/category/scenecategoryspu/createRelate',
        'post',
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          this.linkAttributeChang(this.linkAttributeValue);
        }
      });
    },
    // 批量取消关联
    bathDelFun () {
      let data = {
        sceneCategoryUuid: this.uuid,
        productUuidList: this.productUuidList.join(',')
      };
      // 创建分类
      ApiRequest(
        '/sysback/category/scenecategoryspu/deleteRelate',
        'post',
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          this.linkAttributeChang(this.linkAttributeValue);
        }
      });
    }
  }
};
</script>
